<?php

namespace app\web\controller;

use app\common\model\Users;
use controller\BasicWeb;
use service\InterfaceCode;
use think\facade\Cache;
use think\facade\Config;

class Login extends BasicWeb
{
    protected $auth_type = 4;

    //登录
    public function index()
    {
        $mobile = $this->request->param('mobile','');
        $pass = $this->request->param('passwd/s','');
        $ret = $this->auth->login($mobile, $pass);
        if (!$ret) {
            $this->error(InterfaceCode::$app_error_code['PARAMETER_ERROR'], $this->auth->getError());
        }
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success($data);
    }

    //注册
    public function register()
    {
        $data = $this->request->param();
        //验证手机号
        if(!is_mobile($data['mobile'])){
            $this->error(InterfaceCode::$app_error_code['PARAMETER_ERROR'], '手机号格式不正确');
        }
        //查询手机号是否已经注册
        $only_mobile = Users::getByMobile($data['mobile']);
        if($only_mobile){
            $this->error(InterfaceCode::$app_error_code['PARAMETER_ERROR'], '该手机号已经注册');
        }
        if (!$data['mobile_code']){
            $this->error(InterfaceCode::$app_error_code['PARAMETER_ERROR'], '验证码不能为空');
        }
        //验证手机验证码
        $code_key = Config::get('sms_verifycode_pre') . $data['mobile'];
        $code = Cache::store('redis')->get($code_key);
        if($data['mobile_code'] != $code){
            $this->error(InterfaceCode::$app_error_code['PARAMETER_ERROR'], '验证码过期或输入错误');
        }
        $ref = isset($data['ref']) ? trim($data['ref']) : '';

        $param = [
            'mobile' => $data['mobile'],
            'passwd' => $data['passwd'],
            'ref' => $ref
        ];
        // 用户来源
        if($ref != '') {
            $user = Users::getBySpreadCode($ref);
            if($user) {
                $param['parent_id'] = $user->uid;
                $param['second_id'] = $user->parent_id;
            }
        }
        $result = $this->auth->register($param);
        if(!$result) {
            $this->error(InterfaceCode::$app_error_code['PARAMETER_ERROR'], $this->auth->getError());
        }

        $this->success(['userinfo' => $this->auth->getUserinfo()]);
    }

    //通用注销登录
    public function logout()
    {
        $this->auth->logout();
        $this->success();
    }
}
